import { channelList } from '@/apis';
import { IChannel } from '@/types';
import { getUserInfo } from '@/utils';
import { useMap } from 'ahooks';
import { useCallback, useEffect, useMemo } from 'react';
import { atom, useRecoilState } from 'recoil';

interface IChannelState {
    /**
     * if inited
     */
    init: boolean;
    /**
     * category list
     */
    data: IChannel[];
}

/**
 * channel data
 */
const channelState = atom<IChannelState>({
    key: 'channel',
    default: {
        init: false,
        data: []
    }
});

/**
 * 渠道-区域
 */
function useChannel() {
    const [val, setVal] = useRecoilState(channelState);
    const [channelMap, { set }] = useMap<number, string>();
    const user = useMemo(() => getUserInfo(), []);

    const update = useCallback(
        () => {
            channelList(user.brandID)
                .then(res => {
                    setVal({
                        init: true,
                        data: res
                    });
                });
        }, 
        []
    );

    useEffect(() => {
        if (!val?.init) {
            update();
        }
    }, []);
    
    useEffect(() => {
        val.data.forEach(d => {
            set(d.Id, d.ChannelName);
            d.Children.forEach(dist => {
                set(dist.Id, dist.ChannelName);
            })
        })
    }, [val.data]);

    const res: [
        IChannel[],
        Map<number, string>,
        () => void
    ] = [
        val.data,
        channelMap,
        update
    ];

    return res;
}


export {
    channelState,
    useChannel
};
